package com.pubsys.main.client.aplicacao;

import java.util.HashMap;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.pubsys.main.client.util.HistoryTokensHelper;


/**
 * Wrapper class that controls back and forth button hit of browser
 * @author Martin Reus
 *
 */
public class AppHistoryController implements ValueChangeHandler<String>{
	private static AppHistoryController controller = null;
	public String actualAnchor = "";
	
	/**
	 * should not be instantiated by other classes
	 */
	private AppHistoryController() {
		
	}
	
	/**
	 * Has to be unique, therefore the singleton instance
	 * @return
	 */
	public static AppHistoryController getInstance(){
		if (controller == null)
			controller = new AppHistoryController();
		return controller;
	}
	
	
	/**
	 * If not started, application won't work
	 */
	public void start(){
		HistoryTokensHelper.addValueChangeHandler(this);
		HistoryTokensHelper.fireCurrentHistoryState();
	}
	
	
	/**
	 * This can and should be called by any class who wants to change the application
	 * state. It makes the app change the current view state to another page.
	 * Simply call (from other classes) AppHistoryController.getInstance().navigateToPlace(place_instance)
	 * @param place
	 */
	public void goToActivity(Activity activity){
		HistoryTokensHelper.setHistoryTokenWithParameters(activity.getUniqueActivityName(), activity.getActivityParametersAsHashMap(), false);		

		activity.start();
		
		this.changePage(activity.getView());
	}
	
	
	/**
	 * Whenever a history token changes - this could happen when user changes a parameter on the address bar -
 	 * the method below listens to this change and makes the application change its state.
	 */
	
	public void onValueChange(ValueChangeEvent<String> event) {
//		Window.alert(event.getValue());
		
		String historyAnchor = HistoryTokensHelper.getPageAnchor();
		HashMap<String,String> placeParameters = HistoryTokensHelper.getHistoryTokenParameters();
		
		//returns if there is no change to the actual history token of browser history
		if (historyAnchor != null && !historyAnchor.equals("") && historyAnchor.equals(actualAnchor))
			return;

		Activity activity = ActivityFactory.makeFromBrowserHistory(historyAnchor, placeParameters);
		
		changePage(activity.getView());		
	}

	
	/**
	 * Changes the page (view) of the client
	 * @param view
	 */
	private void changePage(Widget view){
		RootPanel.get("_gwt_mainPanel").clear();		
		RootPanel.get("_gwt_mainPanel").add(view);
	}
	
	
}
